<?php


namespace app\index\controller;


use app\common\controller\Apicommon;
use app\common\controller\Excel;
use app\index\model\Device as DeviceModel;
use app\index\model\DeviceCategory;
use think\Db;

/**
 * 设备管理
 * @package app\index\door
 */
class Device extends Apicommon
{
    use Excel;

    public function initialize()
    {
//        parent::initialize();
        header('Access-Control-Allow-Headers: content-type,authorization,token');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            echo 1;die;
        }
        // 安全校验
        if(empty(session('user_auth.uid'))){
            $this->redirect(url('index/index/login'));
        }else{
            $this->uid = session('user_auth.uid');
        }
    }

    /**
     * 设备类别列表
     * @param int $limit 页面显示数量
     */
    public function device_category_list()
    {
        $row = DeviceCategory::where([])->paginate(input('limit',10));
        $this->assign('row',$row);
        return $this->fetch();
    }

    public function device_category_add()
    {
        if ($this->request->isPost()) {
            $this->request->filter('trim,strip_tags');
            $name = $this->request->request('name');
            $image = $this->request->request('image');
            if (empty($name)) {
                $this->error_json('必填项未填');
            }
            if (DeviceCategory::get(['name' => $name])) {
                $this->error_json('该名称已存在');
            }

            $res = DeviceCategory::create([
                'name' => $name,
                'image' => $image,
            ]);
            if ($res) $this->success_json('添加成功');
        }
        return $this->fetch();
    }

    public function device_category_edit($id = null)
    {
        $this->request->filter('trim,strip_tags');
        $id = $id ?: input('id');
        if (empty($id)) {
            $this->error_json('参数错误');
        }
        $cate = DeviceCategory::get($id);
        if (!$cate) {
            $this->error_json('类别不存在');
        }
        if ($this->request->isPost()) {
            $name = input('name');
            if (empty($name)) {
                $this->error_json('必填项未填');
            }
            if (DeviceCategory::where('name', 'eq', $name)->where('id', 'neq', $id)->find()) {
                $this->error_json('该名称已存在');
            }
            $cate->name = $name;
            $cate->image = input('image');
            $cate->save();
            $this->success_json('修改成功');
        }
        $this->assign('row', $cate);
        return $this->fetch();
    }

    public function device_category_del()
    {
        $ids = input('id');
        $category = DeviceCategory::whereIn('id',$ids)->select();
        foreach ($category as $item) {
            $item->delete();
        }
        $this->success_json('删除成功');
    }

    public function device_list()
    {
        $serial = input('device_serial');
        $where = [];
        if (!empty($serial)){
            $where[] = ['device_serial','eq',$serial];
        }
        $device = DeviceModel::where($where)->paginate(input('limit',10))->each(function ($item) {
            $arr_status = ['','使用中','充电中','空闲中','安检中','超时未安检','已报废'];
            $item['status'] = isset($arr_status[$item['status']]) ? $arr_status[$item['status']] : '未知';
            $gear = Db::name('door')->where('id',$item['door_id'])->value('gear_id');
            $item['gear'] = Db::name('gear')->where('id',$gear)->value('gear_model');
            $item['door'] = Db::name('door')->where('id',$item['door_id'])->value('door_serial');
            return $item;
        });
        $device_category = DeviceCategory::field('id,name')->select();
        $device_name = DeviceModel::distinct('device_name')->column('device_name');
        $device_model = DeviceModel::distinct('device_model')->column('device_model');
        $device_status = [1 => '使用中', 3 => '空闲中', 4 => '安检中', 5 => '超时未安检', 6 => '已报废'];
        $this->assign('device_category', $device_category);
        $this->assign('device_model', $device_model);
        $this->assign('device_name', $device_name);
        $this->assign('device_status', $device_status);
        $this->assign('device',$device->items());
        $this->assign('pages',$device->render());
        return $this->fetch();
    }

    public function device_add()
    {
        if ($_POST){
            $serial = input('serial');
            $device_name = input('device_name');
            $model = input('model');
            $check_time = input('check_time');
            $warning_time = input('warning_time');
            $scrap_time = input('scrap_time');
            $rfid = input('rfid');
            $category_id = input('category_id');
            if (empty($serial) || empty($device_name) ||empty($model) || empty($check_time) || empty($warning_time) || empty($scrap_time)|| empty($category_id)){
                return $this->ajaxReturn(1,'必填项未填写');
            }
            // 设备编号冲突检查
            $serial_check = DeviceModel::where(['device_serial'=>$serial])->find();
            if ($serial_check) {
                return $this->ajaxReturn(1,'设备编号已存在');
            }

            // 检查电子标签
            $rfid_check = DeviceModel::get(['rfid'=>$rfid]);
            if ($rfid_check) {
                return $this->ajaxReturn(1,'电子标签号已存在');
            }

            $res = Db::name('device')->insertGetId([
                'device_name'=>$device_name,
                'device_serial'=>$serial,
                'device_model'=>$model,
                'check_time'=>$check_time,
                'warning_time'=>$warning_time,
                'scrap_time'=>$scrap_time,
                'rfid'=>$rfid,
                'category_id'=>$category_id
            ]);
            if ($res){
                return $this->ajaxReturn(0,'添加成功');
            }
            return $this->ajaxReturn(1,'添加失败');
        }
        $category_list = DeviceCategory::all();
        $this->assign('category_list',$category_list);
        return $this->fetch();
    }

    public function device_edit($id = null)
    {
        $id = $id ?: input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        if ($_POST){
            $serial = input('serial');
            $device_name = input('device_name');
            $model = input('model');
            $check_time = input('check_time');
            $warning_time = input('warning_time');
            $scrap_time = input('scrap_time');
            $rfid = input('rfid');
            $category_id = input('category_id');
            if (empty($serial) || empty($device_name) ||empty($model) || empty($check_time) || empty($warning_time) || empty($scrap_time)|| empty($category_id)){
                return $this->ajaxReturn(1,'必填项未填写');
            }

            // 设备编号冲突检查
            $serial_check = DeviceModel::where([
                ['device_serial','=',$serial],
                ['id','neq',$id]
            ])->whereOr(function ($query) use ($id, $rfid) {
                $query->where([
                    ['rfid', '=', $rfid],
                    ['id', '<>', $id]
                ]);
            })->find();

            if ($serial_check) {
                return $this->ajaxReturn(1,'设备编号或电子标签已存在');
            }

            $res = Db::name('device')->where('id',$id)->update([
                'device_name'=>$device_name,
                'device_serial'=>$serial,
                'device_model'=>$model,
                'check_time'=>$check_time,
                'warning_time'=>$warning_time,
                'scrap_time'=>$scrap_time,
                'rfid'=>$rfid,
                'category_id'=>$category_id
            ]);
            if ($res){
                return $this->ajaxReturn(0,'编辑成功');
            }
            return $this->ajaxReturn(1,'编辑失败');
        }
        $device = Db::name('device')->where('id',$id)->find();
        $category_list = DeviceCategory::all();
        $this->assign('device',$device);
        $this->assign('category_list',$category_list);
        return $this->fetch();
    }

    public function device_del()
    {
        $id = input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        $ids = explode(',',$id);
        $res = DeviceModel::whereIn('id',$ids)->delete();
        if ($res){
            return $this->ajaxReturn(0,'删除成功');
        }
        return $this->ajaxReturn(1,'删除失败');
    }

    public function device_list_export()
    {
        $device = Db::name('device')->select();
        $data = [];
        foreach ($device as $key => $value){
            $arr_status = ['','使用中','充电中','空闲中','安检中','超时未安检','已报废'];
            $status = isset($arr_status[$value['status']]) ? $arr_status[$value['status']] : '未知';
            $gear = Db::name('door')->where('id',$value['door_id'])->value('gear_id');

            // 重新排序
            $temp['device_serial'] = $value['device_serial'];
            $temp['device_name'] = $value['device_name'];
            $temp['device_model'] = $value['device_model'];
            $temp['status'] = $status;
            $temp['gear'] = Db::name('gear')->where('id',$gear)->value('gear_model');
            $temp['rfid'] = $value['rfid'];
            $temp['door'] = Db::name('door')->where('id',$value['door_id'])->value('door_serial');
            $temp['check_time'] = $value['check_time'];
            $temp['scrap_time'] = $value['scrap_time'];
            $data[] = $temp;
        }
        $this->exportExcel('设备列表',[
            '编号',
            '设备名称',
            '型号',
            '状态',
            '所属智能柜',
            '电子标签',
            '所在柜门',
            '检修时间',
            '报废时间',
        ],$data);
    }

}